<?php

namespace App\Http\Controllers\Supplier;

use App\Models\Order;
use App\Models\OrderLog;
use App\Models\OrderRate;
use App\Models\OrderRefund;
use App\Models\ShopSms;
use App\Models\OrderLease;
use App\Models\ShopUser;
use App\Services\CommonService;
use App\Services\GoodsService;
use App\Services\OrderService;
use App\Services\OtherCallbacksService;
use Illuminate\Http\Request;

class OrderRefundController extends BaseController
{
    /**
     * 订单退款列表
     */
    public function orderRefundList(Request $request){
        $request_data = $request->all();
        $user = $this->users;
        $list = OrderRefund::orderRefundList($request_data,OrderRefund::ORDER_REFUND_TYPE_ONLY_REFUND,$user['user_id']);
        if(!empty($list) && !empty($list['data'])){
            foreach ($list['data'] as $k=>$v){
                $list['data'][$k]['refund_status_name'] = OrderRefund::ORDER_REFUND_STATUS_NAME_LIST[$v['refund_status']];
            }
        }
        return ReturnMsg(CommonService::HTTP_CODE_SUCCESS,'获取成功',$list);
    }

    /**
     * 订单退款 - 商户审核通过
     */
    public function shopCheckPass(Request $request){
        $refund_id = $request->input('refund_id');
        if(!empty($refund_id)){
            $order = OrderRefund::from('sp_order_refund as or')->where('or.id',$refund_id)
                ->wherein('or.refund_status',[OrderRefund::ORDER_REFUND_NOCHECK,OrderRefund::ORDER_REFUND_ADMIN_REFUSE])
                ->leftjoin('sp_order_2 as o','or.order_id','o.id')
                ->leftjoin('sp_shop_user_2 as s','s.member_id','o.seller_id')
                ->leftjoin('sp_order_goods_2 as og','og.order_id','o.id')
                ->select('or.id', 'o.mini_id', 'o.uid','or.order_id','o.realname','o.mobile','o.pay_type','o.status','o.rent_total','o.rights_auth_no','o.trade_no','o.alipay_trade_no','o.seller_id','o.month_total','o.uid','o.order_from','o.financing_type','o.is_skip','s.shop_balance','og.goods_title','o.payer_user_id','og.goods_id','o.settlement_status','o.huabei_fee_bear','o.pay_time','s.refund_check','s.shopname','or.deduct_amount','o.flow_id')->first();
            $order = $order ? $order->toArray() : [];
            if(!empty($order)){
                // if(OrderRate::where('order_id',$order['order_id'])->count() == 0){
                //     return ReturnMsg(CommonService::HTTP_CODE_FAIL, '订单来源费率未设置,请联系平台客服');
                // }
                if($order['deduct_amount'] > ShopUser::where('member_id',$order['seller_id'])->value('shop_balance')){
                    return ReturnMsg(CommonService::HTTP_CODE_REFUND, '商户余额不足，请充值后再退款');
                }
                if($order['refund_check'] == ShopUser::ORDER_REFUND_ADMIN_CHECK_ENABLE){//需要平台审核 提交至平台审核
                    $res = OrderRefund::where('id',$refund_id)->update(['refund_status'=>OrderRefund::ORDER_REFUND_SHOP_CHECKED]);
                    $order_res = Order::where('id',$order['order_id'])->update(['status'=>OrderService::ORDER_STATUS_APPLY_REFUND_SHOP_PASS,'update_time'=>time()]);
                    if($res && $order_res){
                        OrderLog::addOrderLog($order['order_id'],$this->users['id'],OrderLog::ORDER_LOG_OPERATE_TYPE_ADMIN,'订单退款-商户审核通过');
                        return ReturnMsg(CommonService::HTTP_CODE_SUCCESS,'审核成功');
                    }else{
                        return ReturnMsg(CommonService::HTTP_CODE_FAIL, '审核失败');
                    }
                }elseif($order['refund_check'] == ShopUser::ORDER_REFUND_ADMIN_CHECK_DISABLE){//不需要平台审核   直接退款
                    $order_lease = OrderLease::where([['order_id',$order['order_id']],['status',OrderLease::ORDER_LEASE_STATUS_PAID]])->select('id')->get();
                    $order_lease = $order_lease ? $order_lease->toArray() : [];
                    $lease_id_arr = array_column($order_lease,'id');
                    $res = OrderRefund::orderRefund($order,$lease_id_arr,OrderRefund::ORDER_REFUND_REQUEST_TYPE_XXZ,OrderRefund::ORDER_REFUND_ALLIN);
                    if($res['status'] == CommonService::HTTP_CODE_SUCCESS){
                        $user_order_count = Order::where('uid',$order['uid'])->whereIn('status',OrderService::getOrderStatus(OrderService::ORDER_MANUAL_WITHHOLD_OR_PAY))->count();
                        Order::where('uid',$order['uid'])->whereIn('status',OrderService::getOrderStatus(OrderService::ORDER_MANUAL_WITHHOLD_OR_PAY))->update(['user_order_count'=>$user_order_count]);
                        OrderLog::addOrderLog($order['order_id'],$this->users['id'],OrderLog::ORDER_LOG_OPERATE_TYPE_ADMIN,'订单退款-商户审核通过');
                        OtherCallbacksService::orderRefundNotify($order['order_id'],date('Y-m-d H:i:s'));
                        //退款成功短信通知
                        ShopSms::orderRefundSuccess($order['seller_id'],$order['realname'],$order['trade_no'],$order['mobile'],$order['order_id'],$this->users['id']);
                        return ReturnMsg(CommonService::HTTP_CODE_SUCCESS,'退款成功');
                    }else{
                        return ReturnMsg(CommonService::HTTP_CODE_SUCCESS,'退款失败',$res);
                    }
                }
            }else{
                return ReturnMsg(CommonService::HTTP_CODE_FAIL, '订单不存在');
            }
        }else{
            return ReturnMsg(CommonService::HTTP_CODE_FAIL, '请选择要操作的订单');
        }
    }




    /**
     * 订单退款 - 商户审核拒绝
     */
    public function shopCheckRefuse(Request $request){
        $refund_id = $request->input('refund_id');
        $refuse_reason = $request->input('refuse_reason');
        if(!empty($refund_id) && !empty($refuse_reason)){
            $order_id = OrderRefund::where([['id',$refund_id],['refund_status',OrderRefund::ORDER_REFUND_NOCHECK]])->value('order_id');
            if(!empty($order_id)){
                $data['refuse_reason'] = $refuse_reason;
                $data['refund_status'] = OrderRefund::ORDER_REFUND_SHOP_REFUSE;
                $res = OrderRefund::where('id',$refund_id)->update($data);
                $order_res = Order::where('id',$order_id)->update(['status'=>OrderService::ORDER_STATUS_APPLY_REFUND_SHOP_REFUSE,'update_time'=>time()]);
                if($res && $order_res){
                    OrderLog::addOrderLog($order_id,$this->users['id'],OrderLog::ORDER_LOG_OPERATE_TYPE_ADMIN,'订单退款-商户审核拒绝');
                    return ReturnMsg(CommonService::HTTP_CODE_SUCCESS,'审核拒绝成功');
                }else{
                    return ReturnMsg(CommonService::HTTP_CODE_FAIL, '审核拒绝失败');
                }
            }else{
                return ReturnMsg(CommonService::HTTP_CODE_FAIL, '退款订单不存在或不是待审核状态');
            }
        }else{
            return ReturnMsg(CommonService::HTTP_CODE_FAIL, '请选择要操作的订单并填写拒绝原因');
        }
    }

    /**
     * 退款详情
     */
    public function orderRefundInfo(Request $request){
        $order_id = $request->input('order_id');
        if(!empty($order_id)){
            $order_refund = OrderRefund::from('sp_order_refund as or')->where('or.order_id',$order_id)
                ->leftjoin('sp_order_2 as o','or.order_id','o.id')
                ->leftjoin('sp_order_goods_2 as og','og.order_id','o.id')
                ->select('or.id','o.trade_no','or.create_time','or.refund_amount','or.deduct_amount','or.paid_total_rent','og.goods_title','og.imgurl','og.setmeal_title','o.amount','og.lease_set','og.lease_time','o.rent_total','or.refund_type','or.refund_reason','or.refund_desc','or.refund_image','or.refund_status')->orderBy('or.id','desc')->first();
            $order_refund = obToArray($order_refund);
            if(!empty($order_refund)){
                $order_refund['refund_status_name'] = OrderRefund::ORDER_REFUND_STATUS_NAME_LIST[$order_refund['refund_status']];
            }
            $order_refund['order_log'] = OrderLog::getOrderLogByOrderId($order_id);
            return ReturnMsg(CommonService::HTTP_CODE_SUCCESS,'获取成功',$order_refund);
        }else{
            return ReturnMsg(CommonService::HTTP_CODE_FAIL, '请选择要查看的订单');
        }
    }


    /**
     * 退款订单补足金额明细
     */
    public function orderRefundTransData(Request $request){
        $refund_id = $request->input('refund_id');
        if(!empty($refund_id)){
            $order_refund = OrderRefund::from('sp_order_refund as or')->where('or.id',$refund_id)
                ->leftjoin('sp_order_2 as o','or.order_id','o.id')
                ->leftjoin('sp_order_goods_2 as og','og.order_id','o.id')
                ->leftjoin('sp_shop_user_2 as s','s.member_id','o.seller_id')
                ->leftjoin('sp_order_rate as oe','oe.order_id','or.order_id')
                ->select('or.id','or.order_id','o.trade_no','o.pay_type','o.month_total','o.rent_total','or.deduct_amount','or.paid_total_rent','or.refund_amount','o.is_skip','o.financing_type','og.goods_id','o.month_total','o.status','o.rights_auth_no','o.alipay_trade_no','o.seller_id','o.uid','o.order_from','s.shop_balance','og.goods_title','o.payer_user_id','o.settlement_status','o.huabei_fee_bear','o.pay_time','s.shopname','oe.fixed_amount','oe.shop_rate','oe.platform_rate','oe.withhold_rate','oe.file_rate','oe.financing_rate','oe.insure_rate','oe.huabei_rate','o.huabei_stages')->first();
            $order_refund = obToArray($order_refund);
            if(!empty($order_refund)){
                $insure_fee = 0;

                $data['refund_id'] = $order_refund['id'];
                $data['trade_no'] = $order_refund['trade_no'];
                $data['pay_type'] = OrderLease::ORDER_LEASE_PAY_TYPE_LIST[$order_refund['pay_type']];
                $data['month_total'] = $order_refund['month_total'];
                $data['rent_total'] = $order_refund['rent_total'];
                $data['paid_total_rent'] = $order_refund['paid_total_rent'];
                if($order_refund['is_skip'] == Order::RISK_SKIP_YES){
                    $data['is_risk'] = '否';
                }else{
                    $data['is_risk'] = '是';
                }
                $data['financing_type'] = Order::FINANCING_TYPE_LIST[$order_refund['financing_type']];
                $data['insure_fee'] = $insure_fee;
                $data['refund_amount'] = $order_refund['refund_amount'];
                $data['paid_service_fee'] = 0;
                $data['total_service_fee'] = 0;
                $order_lease = OrderLease::where('order_id',$order_refund['order_id'])->select('id','status','settle_type','paid_rent','which_period','rent')->get();
                $order_lease = obToArray($order_lease);
                $data['deduct_refund_amount'] = 0;
                $data['deduct_service_fee'] = 0;
                if($order_refund['huabei_fee_bear'] == GoodsService::GOODS_HUABEI_FEE_MERCHANT && $order_refund['pay_time'] + 15*24*3600 > time()){
                    $order_refund['shop_rate'] = $order_refund['shop_rate'] - $order_refund['huabei_rate'];
                }
                if($order_lease){
                    foreach ($order_lease as $k=>$v){
                        if($v['status'] == OrderLease::ORDER_LEASE_STATUS_PAID || $v['status'] == OrderLease::ORDER_LEASE_STATUS_REFUNDED || $v['status'] == OrderLease::ORDER_LEASE_STATUS_BUYOUT){
                            $shop_rate = $order_refund['shop_rate'];
                        }
                        if($v['settle_type'] == OrderLease::ORDER_LEASE_SETTLE_STATUS_YES){
                            if($v['status'] != OrderLease::ORDER_LEASE_STATUS_REFUNDED){
                                $data['deduct_refund_amount'] += $v['paid_rent'];
                            }
                            if($v['which_period'] == 1){
                                $service_fee = sprintf("%01.4f",$v['paid_rent'] * $shop_rate * 0.01 + $order_refund['fixed_amount']);
                            }else{
                                $service_fee = sprintf("%01.4f",$v['paid_rent'] * $shop_rate * 0.01);
                            }
                            $data['paid_service_fee'] += $service_fee;
                            $data['total_service_fee'] += $service_fee;
                        }else{
                            if($v['status'] == OrderLease::ORDER_LEASE_STATUS_REFUNDED){
                                if($v['which_period'] == 1){
                                    $data['paid_service_fee'] += $order_refund['fixed_amount'];
                                    $data['total_service_fee'] += $order_refund['fixed_amount'];
                                }
                            }else{
                                $data['paid_service_fee'] += 0;
                                $data['deduct_service_fee'] += 0;
                                if($v['which_period'] == 1){
                                    $data['deduct_service_fee'] += $order_refund['fixed_amount'];
                                    $data['total_service_fee'] += $order_refund['fixed_amount'];
                                }
                            }
                        }
                    }
                }
                $data['deduct_amount'] = sprintf("%01.4f",$data['deduct_refund_amount'] + $data['deduct_service_fee']);
                return ReturnMsg(CommonService::HTTP_CODE_SUCCESS,'获取成功',$data);
            }else{
                return ReturnMsg(CommonService::HTTP_CODE_FAIL, '订单不存在');
            }
        }else{
            return ReturnMsg(CommonService::HTTP_CODE_FAIL, '请选择要查看的订单');
        }
    }


    /**
     * 退款账单明细
     */
    public function orderRefundDetail(Request $request){
        $refund_id = $request->input('refund_id');
        if(!empty($refund_id)){
            $order = OrderLease::from('sp_order_lease_2 as ol')->where('or.id',$refund_id)
                ->leftjoin('sp_order_refund as or','or.order_id','ol.order_id')
                ->leftjoin('sp_order_rate as oe','oe.order_id','ol.order_id')
                ->leftjoin('sp_order_2 as o','o.id','ol.order_id')
                ->select('ol.id','o.is_skip','o.trade_no','o.financing_type','o.huabei_fee_bear','ol.which_period','ol.pay_type','ol.settle_type','ol.status','ol.settle_amount','ol.rent','ol.paid_rent','oe.platform_rate','oe.shop_rate','oe.fixed_amount','oe.smartcontract_amount','oe.realname_amount','oe.risk_amount','oe.platform_rate','oe.withhold_rate','oe.file_rate','oe.financing_rate','oe.insure_rate','oe.huabei_rate','o.pay_time')->get();
            $order = obToArray($order);
            if(!empty($order)){
                $total_payable_fee = 0;
                $total_paid_fee = 0;
                $total_refund_amount = 0;
                $total_deduct_fee = 0;
                $total_deduct_amount = 0;
                foreach ($order as $k=>$v){
                    $order[$k]['paid_fee'] = 0;
                    $order[$k]['refund_amount'] = 0;
                    $order[$k]['deduct_amount'] = 0;
                    $order[$k]['deduct_refund_amount'] = 0;
                    $order[$k]['deduct_fee'] = 0;
                    $order[$k]['payable_fee'] = 0;
                    if($v['huabei_fee_bear'] == GoodsService::GOODS_HUABEI_FEE_MERCHANT && $v['pay_time'] + 15*24*3600 > time()){
                        $shop_rate = $v['shop_rate'] - $v['huabei_rate'];
                    }else{
                        $shop_rate = $v['shop_rate'];
                    }
                    if($v['which_period'] == 1){//首期
                        if($v['settle_type'] != OrderLease::ORDER_LEASE_SETTLE_STATUS_YES){//未结算
                            $order[$k]['withhold_rate'] = 0;
                            $order[$k]['file_rate'] = 0;
                            $order[$k]['platform_rate'] = 0;
                            $shop_rate = 0;
                            $order[$k]['payable_fee'] = $v['fixed_amount'];
                        }else{
                            $order[$k]['payable_fee'] = sprintf("%01.4f",$v['rent'] * $shop_rate * 0.01 + $v['fixed_amount']);
                        }
                    }else{
                        $order[$k]['smartcontract_amount'] = 0;
                        $order[$k]['realname_amount'] = 0;
                        $order[$k]['risk_amount'] = 0;
                        if($v['financing_type'] == Order::FINANCING_TYPE_RONG) {//融资
                            if($v['status'] != OrderLease::ORDER_LEASE_STATUS_NOPAY){
                                $order[$k]['withhold_rate'] = 0;
                                $order[$k]['platform_rate'] = 0;
                                $shop_rate = $v['financing_rate'];
                                $order[$k]['shop_rate'] = $shop_rate;
                                $order[$k]['payable_fee'] = sprintf("%01.4f",$v['rent'] * $shop_rate * 0.01);
                            }
                        }else{
                            if($v['settle_type'] == OrderLease::ORDER_LEASE_SETTLE_STATUS_YES){//已结算
                                $order[$k]['payable_fee'] = sprintf("%01.4f",$v['rent'] * $shop_rate * 0.01);
                            }else{
                                $order[$k]['payable_fee'] = 0;
                            }
                        }
                    }

                    $order[$k]['pay_type'] = OrderLease::ORDER_LEASE_PAY_TYPE_LIST[$v['pay_type']];
                    if($v['status'] != OrderLease::ORDER_LEASE_STATUS_NOPAY){
                        $order[$k]['refund_amount'] = $v['paid_rent'];
                    }
                    if($v['settle_type'] == OrderLease::ORDER_LEASE_SETTLE_STATUS_YES){//已结算
                        $order[$k]['paid_fee'] = $order[$k]['payable_fee'];
                    }else{
                        if($v['status'] == OrderLease::ORDER_LEASE_STATUS_REFUNDED){
                            $order[$k]['paid_fee'] = $order[$k]['payable_fee'];
                        }
                    }
                    $order[$k]['pay_status'] = OrderLease::ORDER_LEASE_STATUS_LIST[$v['status']];
                    $order[$k]['settle_status_name'] = OrderLease::ORDER_LEASE_SETTLE_STATUS_LIST[$v['settle_type']];
                    $order[$k]['lease_status_name'] = OrderLease::ORDER_LEASE_STATUS_LIST[$v['status']];
                    if($v['status'] == OrderLease::ORDER_LEASE_STATUS_NOPAY){

                    }else{
                        $order[$k]['deduct_fee'] = sprintf("%01.4f",$order[$k]['payable_fee'] - $order[$k]['paid_fee']);
                    }
                    if($v['settle_type'] == OrderLease::ORDER_LEASE_SETTLE_STATUS_YES && $v['status'] != OrderLease::ORDER_LEASE_STATUS_REFUNDED){
                        $order[$k]['deduct_refund_amount'] = $v['paid_rent'];
                    }
                    $order[$k]['shop_rate'] = $shop_rate;
                    $total_payable_fee += $order[$k]['payable_fee'];
                    $total_paid_fee += $order[$k]['paid_fee'];
                    $total_refund_amount += $order[$k]['refund_amount'];
                    $total_deduct_fee += $order[$k]['deduct_fee'];
                    $total_deduct_amount += $order[$k]['deduct_refund_amount'];
                }
                $order['total_payable_fee'] = sprintf("%01.4f",$total_payable_fee);
                $order['total_paid_fee'] = sprintf("%01.4f",$total_paid_fee);
                $order['total_refund_amount'] = sprintf("%01.4f",$total_refund_amount);
                $order['total_deduct_fee'] = sprintf("%01.4f",$total_deduct_fee);
                $order['total_deduct_amount'] = sprintf("%01.4f",$total_deduct_amount);
            }
            return ReturnMsg(CommonService::HTTP_CODE_SUCCESS,'获取成功',$order);
        }else{
            return ReturnMsg(CommonService::HTTP_CODE_FAIL, '请选择要查看的订单');
        }
    }


}
